package com.hihiwjc.app.zzmh.apis.home;

import android.support.annotation.NonNull;

import com.alibaba.fastjson.JSON;
import com.hihiwjc.app.zzmh.apis.ApiCallback;
import com.hihiwjc.app.zzmh.apis.Apis;
import com.hihiwjc.app.zzmh.apis.BaseJSONApi;
import com.hihiwjc.app.zzmh.entities.BaseEntity;
import com.hihiwjc.app.zzmh.entities.home.Recommend;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest;

/**
 * 主页的Api
 * <br/>Created by hihiwjc on 2015/10/28 0028
 * <br/>Author:hihiwjc
 * <br/>Email:hihiwjc@live.com
 */

public class HomeApi extends BaseJSONApi {
    /**
     * 首页推荐请求地址
     */
    private static final String REQ_METHOD_HOMEPAGE = "homepage";
    private HttpUtils mHttpUtils;
    private ApiCallback mApiCallback;
    public final static int API_ID = 1;
    /**
     * 请求首页推荐的ActionId
     */
    public static final int ACTION_HOME_RECOMMEND = 1;

    public HomeApi(@NonNull HttpUtils httpUtils, @NonNull ApiCallback apiCallback) {
        super(apiCallback, API_ID);
        mHttpUtils = httpUtils;
    }

    /**
     * 请求首页推荐
     */
    public void reqHomeRecommend() {
        setAction_id(ACTION_HOME_RECOMMEND);
        String req_url = Apis.API_URL + REQ_METHOD_HOMEPAGE+"&timestamp=1446051518237&param=%7B%22v%22%3A1%7D&sig=cd0c55c3514fb5545a91ffe4ce337747";
        mHttpUtils.send(HttpRequest.HttpMethod.GET, req_url, this);
    }

    @Override
    public void onSuccess(ResponseInfo<String> responseInfo) {
        switch (actionId()) {
            case ACTION_HOME_RECOMMEND:
                handleHomeRecommend(responseInfo.result);
                break;
        }
    }

    /**
     * 处理首页推荐
     */
    private void handleHomeRecommend(String result) {
        BaseEntity baseEntity = JSON.parseObject(result, BaseEntity.class);
        if (baseEntity.getErrorCode() == 0) {
            Recommend recommend = JSON.parseObject(result, Recommend.class);
            onCallback(recommend);
        } else {
            onCallback(baseEntity);
        }
    }
}
